﻿using System;
using PgBirdie.Core.Config;
using PgBirdie.Core.Model;
using PgBirdie.Core.Model.Database.AccessControl;
using PgBirdie.Core.Model.Database.Structure;
using PgBirdie.Core.Service.DbObject;
using PgBirdie.Core.Service.Infrastructure;

namespace PgBirdie.Core.Service.Dump
{
    /// <summary>
    /// DbObject extraction specifics for sql text from pg_dump.exe.
    /// </summary>
    public class DbObjectFromPgDumpService : DbObjectBase, IDbObjectFromPgDumpService
    {
        public DbObjectFromPgDumpService(ITextFormatService text) : base(text) {}

        public override PgTable GetTable(string text)
        {
            // Examples:
            // CREATE TABLE "TableName" (
            // CREATE UNLOGGED TABLE "TableName" (

            var segments = text.Split(Settings.SplitterFor.Space, StringSplitOptions.RemoveEmptyEntries);

            var table = new PgTable();
            table.ModelType = PgDbObjectType.Table;
            if (segments.Length == 4)
                table.Name = Text.RemoveDoubleQuotes(segments[2]);
            else if (segments.Length == 5 && segments[1].Equals("UNLOGGED", StringComparison.OrdinalIgnoreCase))
            {
                table.Name = Text.RemoveDoubleQuotes(segments[3]);
                table.IsUnlogged = true;
            }
            else
                throw new Exception("Could not extract table name from: " + text);

            return table;
        }

        public override PgOwner GetOwner(string text, PgDbObject target)
        {
            // -- Name: FeedAggregatorSourceError; Type: TABLE; Schema: public; Owner: postgres; Tablespace:
            var segments = text.Split(Settings.SplitterFor.Space, StringSplitOptions.RemoveEmptyEntries);

            var role = new PgRole()
                { Name = Text.RemoveCommaOrSemiColonFromTheEnd(Text.RemoveDoubleQuotes(segments[8])) };

            return new PgOwner(role, target);
        }
    }
}